import Core from "core";
import TokenAuth from "./token";

function authLogin(callback) {
  ((callback, Core, handleLogin) => {
    wx.getSetting({
      success(res) {
        if (!res.authSetting["scope.userInfo"]) {
          wx.authorize({
            scope: "scope.userInfo",
            success() {
              Core.Data.setIsAuth(true);
              handleLogin(callback);
            },
            fail() {
              Core.Data.setIsAuth(false);
              if (callback) callback();
            }
          });
        } else {
          Core.Data.setIsAuth(true);
          handleLogin(callback);
        }
      }
    });
  })(callback, Core, function(callback) {
      let openId = "";
      let unionId = "";
      Core.WeChat.login()
        .then(res => {
          let code = res && res.code;
          return Core.Api.Wx.decrypt(code, "2");
        })
        .then(res => {
          openId = res.data.openid;
          unionId = res.data.unionid;
          return Core.WeChat.getUserInfo();
        })
        .then(res => {
          let userInfo = res.userInfo;
          Core.Data.setWxUser(userInfo);
          // 2代表用户端2.0
          return Core.Api.User.loginByWx(openId, unionId, JSON.stringify(userInfo), 2);
        })
        .then(res => {
          let token = res.token;
          let user = res.user;
          Core.Data.setToken(token);
          Core.Data.setUser(user);
          if (callback) callback();
        })
        .catch(err => {
          console.log(err);
          if (callback) callback();
        });
    }
  );
}

function isLogin() {
  let wxUser = Core.Data.getWxUser() || "";
  return !!wxUser;
}

function getUid(user) {
  if (!user) {
    user = Core.Data.getUser();
  }
  if (user) {
    return user.type === 1 ? `customer_uid_${user.uid.toLowerCase()}` : `doctor_uid_${user.uid.toLowerCase()}`;
  }
  return "";
}

function _auth(url, func) {
  let index = url.indexOf("?");
  let mUrl = url;
  if (index > 0) {
    mUrl = url.substring(0, index);
  }
  if (TokenAuth.hasOwnProperty(mUrl)) {
    let isToken = TokenAuth[mUrl];
    let token = Core.Data.getToken();
    if (isToken && !token) {
      func({ url: "/pages/登录页/main" });
      return true;
    }
  }
  return false;
}

function go(url) {
  let navigateTo = wx.navigateTo;
  if (_auth(url, navigateTo)) {
    return;
  }
  navigateTo({ url: url });
}

function goRedirect(url) {
  let redirectTo = wx.redirectTo;
  if (_auth(url, redirectTo)) {
    return;
  }
  redirectTo({ url: url });
}

function reLaunchGo(url) {
  let reLaunch = wx.reLaunch;
  if (_auth(url, reLaunch)) {
    return;
  }
  reLaunch({ url: url });
}

function switchTab(url) {
  let switchTab = wx.switchTab;
  if (_auth(url, switchTab)) {
    return;
  }
  switchTab({ url: url });
}

function goBack(delta = 1) {
  wx.navigateBack(delta);
}

function funcing() {
  wx.showModal({
    title: "",
    content: "功能开发中,敬请期待",
    showCancel: false
  });
}

function showErrorMsg(msg) {
  wx.showModal({
    title: "",
    content: msg,
    showCancel: false
  });
}

function getHospitalId() {
  let user = Core.Data.getUser();
  if (isLogin() && user.user_track) {
    return user.user_track.hospital_id;
  }
  return 0;
}

let Common = {
  isLogin: isLogin,
  authLogin: authLogin,
  getUid: getUid,
  funcing: funcing,
  go: go,
  goRedirect: goRedirect,
  reLaunchGo: reLaunchGo,
  goBack: goBack,
  switchTab: switchTab,
  showErrorMsg: showErrorMsg,
  getHospitalId: getHospitalId
};

export default Common;
